﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;



namespace Nivdal
{
    public partial class Default : System.Web.UI.Page
    {
        //protected void Page_PreInit(object sender, EventArgs e)
        //{
        //    // in case Membership authentication exists, but the session was cut, need to logout the user.
        //    OnlineUser ou = (OnlineUser)Session["User"]; 
        //    if ((ou.UserId == null) && (HttpContext.Current.User.Identity.IsAuthenticated))
        //    {
        //        FormsAuthentication.SignOut();
        //    }
        
        //}
        protected void Page_Load(object sender, EventArgs e)
        {
            string version = "";
            try { version = ConfigurationManager.AppSettings["version"]; }
            catch { version = "999.0.0.0"; }

            NoamStylesGlobalLiteral.Text = "<link href=\"NoamStyles/Global.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";
            NoamStylesDefaultLiteral.Text = "<link href=\"NoamStyles/Default.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";
            StylesheetNewLiteral.Text = "<link href=\"StyleSheetNew.css?v=" + version + "\" rel=\"stylesheet\" type=\"text/css\" />";

            // url redirection
            if (!IsPostBack)
            {
                string Url = Request.Url.ToString();
                if (!Url.Contains("www") && !(Url.Contains("localhost")) && !(Url.Contains("int.")) && !(Url.Contains("int2.")))
                {
                    string newurl = Url.Replace("http://", "http://www.");
                    //MessageLabel.Text = "will be redirected to: <br /> " + newurl;
                    Response.Redirect(newurl);
                }
            
                DateTime ServerTime = System.DateTime.Now;

                OnlineUser ou = (OnlineUser)Session["User"];
                if (ou.UserId != null)
                {
                    if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        ou.UserId = null;
                        ou.ApprovalStatus = "0";
                        ou.TeamId = null;
                        ou.UserAccessLevel = "0";
                        ou.UserName = null;
                        ou.IsPremium = false;                        
                    }
                    else
                        Response.Redirect("~/RegistrationMessage.aspx");
                }
                else if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    // if authenticated- logout and reload the page
                    FormsAuthentication.SignOut();
                    Response.Redirect("~/Default.aspx");
                }

                //const string crlf = "\r\n";
                //string js = "<script type='text/javascript'>" + crlf +
                //"window.onload=startclock;" + crlf +
                //"var clock;" + crlf +
                //"var time_diff;" + crlf +
                //"function startclock(){" + crlf +
                //   "clock=document.getElementById('clock');" + crlf +
                //   "server_time = new Date('" + ServerTime.ToString("MMMM d, yyyy HH:mm:ss") + "');"
                //   + crlf +
                //   "time_diff=new Date()-server_time;" + crlf +
                //   "setInterval('runclock()',1000);" + crlf +
                //"}" + crlf +
                //"function runclock(){" + crlf +
                //   "var cDate=new Date();" + crlf +
                //   "cDate.setTime(cDate.getTime()-time_diff);" + crlf +
                //   "var curr_year = cDate.getYear();" + crlf +
                //   "var curr_month = cDate.getMonth()+1;" + crlf +
                //   "var curr_day = cDate.getDate();" + crlf +
                //   "var curr_hours = cDate.getHours();" + crlf +
                //   "var curr_mins = cDate.getMinutes();" + crlf +
                //   "var curr_secs = cDate.getSeconds();" + crlf +
                //   "curr_hours=(curr_hours < 10)?'0' + curr_hours:curr_hours;" + crlf +
                //   "curr_mins=(curr_mins < 10)?'0' + curr_mins:curr_mins;" + crlf +
                //   "curr_secs=(curr_secs < 10)?'0' + curr_secs:curr_secs;" + crlf +
                //   "clock.innerHTML=curr_month+'-'+curr_day+'-'+curr_year+'  '+curr_hours+':'+curr_mins+':'+curr_secs;" + crlf +
                //   "}" + crlf +
                //"</script>";

                //Page.RegisterStartupScript("js", js);
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                //this.NumberOfOnlineUsersLabel.Text = (GND.ReadNivdalIntData("Nivdal_GetNumberOfOnlineUsers")).ToString();
                this.NumberOfOnlineUsersLabel.Text = Application["ActiveUsers"].ToString();
                this.NumberOfActiveUsersLabel.Text = NumOfActiveUsers().ToString();

                CultureInfo Cult = ResolveCulture();
                if ((Cult != null) && (Cult.TextInfo.IsRightToLeft))
                {
                    UsersCountPanel.Direction = ContentDirection.RightToLeft;
                    DirStylesheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetRTL.css?v=" + version + "\" />";
                    PostCodePanel.Direction = ContentDirection.RightToLeft;
                    FacebookPanel.Direction = ContentDirection.RightToLeft;
                    //WelcomeTextPanel.Direction = ContentDirection.RightToLeft;
                    //PlayFreePanel.Direction = ContentDirection.RightToLeft;
                    (LoginView1.FindControl("LoginPanel") as Panel).Direction = ContentDirection.RightToLeft;
                    DefaultPanel.Direction = ContentDirection.RightToLeft;
                }
                else 
                {
                    DirStylesheetLiteral.Text = "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheetLTR.css?v=" + version + "\" />";
                }
                //SignupPicture.ImageUrl = ReturnSignUpImageName();
                if (Request.UrlReferrer != null)
                    GND.ExecNivdalSQL("Source", "Nivdal_AddTrafficSource", Request.UrlReferrer.OriginalString);

                WelcomeInfoLabel.Text = GetNivdalData.GetNivdalData.ReplaceLineBreaks(Resources.Resource.Default_WelcomeInfoText);
            

                Title = Resources.Resource.Default_PageTitle;

                if (HttpContext.Current != null)
                {
                    string current_url = HttpContext.Current.Request.Url.ToString();
                    // Debug.WriteLine("current page " + current_url);
                    string prev_url = Request.ServerVariables["HTTP_REFERER"];
                    //Debug.WriteLine("prev page " + prev_url);
                    GND.ExecNivdalSQL("PageName", "Entry", "NewbieTipStage", "UserId", "Nivdal_AddPageStatistic", prev_url, false, Session["NewbieTipStage"], ou.UserId); 
                    GND.ExecNivdalSQL("PageName", "Entry", "NewbieTipStage", "UserId", "Nivdal_AddPageStatistic", current_url, true, Session["NewbieTipStage"], ou.UserId);                    
                }
            }
        }

        protected string ReturnSignUpImageName()
        {
            string[] languages = HttpContext.Current.Request.UserLanguages;
            string language = "en";
            if ((languages != null) && (languages[0] != null))
            {
                language  = languages[0].ToLowerInvariant().Trim().Substring(0,2);
            }
            
            string ReturnValue;

            if (language == "en" || language == "he" || language == "ru" || language == "vi" ||
                language == "el" || language == "de" || language == "es" || language == "it" ||
                language == "sv")
                ReturnValue = "~/Images/SignFreeImages/signfree_" + language + ".png";
            else
                ReturnValue = "~/Images/SignFreeImages/signfree_en.png";

            return ReturnValue;
        }

        public static CultureInfo ResolveCulture()
        {
            string[] languages = HttpContext.Current.Request.UserLanguages;
            if (languages == null || languages.Length == 0)
                return null;
            try
            {
                string language = languages[0].ToLowerInvariant().Trim();
                return System.Globalization.CultureInfo.CreateSpecificCulture(language);
            }
            catch (ArgumentException)
            {
                return null;
            }
        }


        protected int NumOfActiveUsers()
        {

            int ReturnValue = 0;
            string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection
            strConnection = new System.Data.SqlClient.SqlConnection(conn);
            string StrSQL = "Nivdal_GetNumberOfActiveUsers";
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ROWCOUNT", System.Data.SqlDbType.Int, 0));
            cmd.Parameters["@ROWCOUNT"].Direction = ParameterDirection.ReturnValue;

            
            try
            {
                strConnection.Open();
                cmd.ExecuteNonQuery();
                ReturnValue = (int)(cmd.Parameters["@ROWCOUNT"].Value);

            }
            catch (Exception SQLDBException)
            {
                Response.Write(SQLDBException.Message);
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "<script type=\"text/javascript\">alert('" + SQLDBException.Message + "');</script>");
                ReturnValue = 0;
            }

            finally
            {

                strConnection.Close();
            }
            return ReturnValue;

        }

        protected void SubmitCode(object sender, EventArgs e)
        {
            if (CodeTextBox.Text.Trim() == "mhkkl")
            {
                CodePanel.Visible = false;
                PostCodePanel.Visible = true;
                Session["shmdb"] = true;
            }
        }

        protected void UserSessionLoginUpdate(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UserId = GND.ReturnUserId();
            OnlineUser ou = new OnlineUser();
            ou.UserId = GND.ReturnUserId();
            ou.UserName = GND.ReadNivdalStringData("UserId", "Nivdal_GetUserNameById", ou.UserId);
            ou.TeamId = GND.ReadNivdalIntData("@UserId", "Nivdal_GetTeamIdByUserId", ou.UserId);
            ou.UserAccessLevel = GND.ReadNivdalIntData("@UserId", "Nivdal_GetUserLevel", ou.UserId);
            ou.Language = GND.GetUserLanguage();
            ou.IsPremium = GND.IsUserPremium();
            Session["User"] = ou;            
        }


        
    }

    
}
